package com.blrs.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 短信发送工具类
 */
public class SmsHttpApi {

    /**
     * 发送短信
     *
     * @param account 账号
     * @param password 密码
     * @param mobile 手机号
     * @param extno 扩展码
     * @param content 短信内容
     * @param level 短信等级
     * @return 发送结果
     */
    public static String sendMtMessage(String account, String password, String mobile,
                                     String extno, String content, String level) throws Exception {
        // 时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());

        // 密码加密
        String md5Pwd = DigestUtils.md5Hex(password + timestamp);

        // 请求参数
        String param = "account=" + account + "&password=" + md5Pwd + "&mobile=" + mobile +
                "&content=" + content + "&extno=" + extno + "&level=" + level + "&timestamp=" + timestamp;

        // 发送请求
        URL url = new URL("http://112.74.139.4:8002/sms/norsubmit");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(3000);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // 发送数据
        try (OutputStream out = conn.getOutputStream()) {
            out.write(param.getBytes(StandardCharsets.UTF_8));
            out.flush();
        }

        // 读取响应
        StringBuilder result = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        }

        return result.toString();
    }
} 